﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PCRemotePCver
{
    // State object for reading client data asynchronously
    public class StateObject
    {
        // Client  socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 1024;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousSocketListener
    {
        // Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        public static Socket listener;
        public static Socket client;
        public static bool IsClosed = false;
        public static int PORTLISTENING = 1992;
        public AsynchronousSocketListener()
        {
        }

        public static void StartListening()
        {
            // Establish the local endpoint for the socket.
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, PORTLISTENING);

            // Create a TCP/IP socket.
            listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                while (true)
                {
                    try
                    {
                        listener.Bind(localEndPoint);
                        break;
                    }
                    catch (Exception) //If PORTLISTENING has been used
                    {
                        PORTLISTENING = new Random().Next(1000, 9999);
                        localEndPoint = new IPEndPoint(IPAddress.Any, PORTLISTENING);
                    }  
                }
                MainForm mainForm = (MainForm)Application.OpenForms["MainForm"];
                if (mainForm != null)
                    mainForm.ChangePortText(PORTLISTENING);
                listener.Listen(1);
                Console.WriteLine("Started server " + localEndPoint.Address + " at port " + localEndPoint.Port);
                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    Console.WriteLine("Waiting for a connection...");
                    if (!IsClosed)
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
                    else
                    {
                        break;
                    }
                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            if (IsClosed)
                return;
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            if (listener.Available != 0)
                return;
            Socket handler = listener.EndAccept(ar);
            Debug.Print("*********Client {0} connected! ************", ((IPEndPoint)handler.RemoteEndPoint).Address);


            // Create the state object.
            StateObject state = new StateObject();
            client = state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            if (IsClosed)
                return;
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            try
            {
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read 
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // All the data has been read from the 
                        // client. Display it on the console.
                        //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        //    content.Length, content);
                        CommandExecution.ExcuseCommand(content);
                        state.sb.Clear();

                        //Repeat receive async
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                }
            }
            catch (Exception)
            {
                Debug.Print("*********Client {0} has disconnected! ************", ((IPEndPoint)handler.RemoteEndPoint).Address);
                return;
            }
            
        }

        private static void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        public static void SendImage(byte[] imageBytes)
        {
            if (listener == null)
            {
                MessageBox.Show("Connection lost!");
                return;
            }

            byte[] endOfMessage = System.Text.Encoding.UTF8.GetBytes("image_end");
            byte[] bytesToSend = new byte[endOfMessage.Length + imageBytes.Length];
            Buffer.BlockCopy(imageBytes, 0, bytesToSend, 0, imageBytes.Length);
            Buffer.BlockCopy(endOfMessage, 0, bytesToSend, imageBytes.Length, endOfMessage.Length);

            client.BeginSend(bytesToSend, 0, bytesToSend.Length, 0,
                    new AsyncCallback(SendCallback), client);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
